from flask import Flask, render_template, request

from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text
from flask_migrate import Migrate

app = Flask(__name__)

#数据库链接

HOSTNAME = "896d4cc1ece64cf892081e57ce06b5c9in01.internal.cn-north-4.mysql.rds.myhuaweicloud.com"
# MySQL监听的端口号，默认3306
PORT = 3306
# 连接MySOL的用户名
USERNAME = "hwtest_rds_gqsh"
# 连接MySQL的密码
PASSWORD = "iakZqKpM5qRbCo1nLFrb"

DATABASE = "test_gqsh_pos_business"
app.config[
    #'SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&useSSL=false&rewriteBatchedStatements=true"
   'SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8"

db = SQLAlchemy(app)


with app.app_context():
    with db.engine.connect() as conn:
        rs = conn.execute(text("select count(1) from t_sys_action_message "))
        print(rs.fetchone())  # (1,)


class User:
    def __init__(self, username, email):
        self.username = username;
        self.email = email;

#1.使用类传参 & 使用字典传参
@app.route('/')
def hello_world():
    p1 = User("知了", "sdf@qq.com")
    print(p1.email)
    p2 ={
        "username":"张三",
        "email":"dddddddd@qq.com"
    }
    #return render_template('index.html',user=p1)
    return render_template('index.html',user=p1,person=p2)

#2.带参数的url
@app.route('/blog/<blog_id>')
def blog_detail(blog_id):
    return render_template("blog_detail.html",blog_id = blog_id ,username = '知了')

#3.参数带类型的
@app.route('/blogin/<int:blog_id>')
def blog_detail1(blog_id):
    return '您访问的博客是：%s' % blog_id

#4.获取第二页数据 /book/list?page=2
@app.route('/book/list')
def book_list():
    page = request.args.get("page",default=1,type=int)
    #return '您获取的是第%s 页' %page
    return f'您获取的是第 {page} 页'

#5.if&for 控制及循环
@app.route('/control')
def control_statement():
    age = 18
    books=[{
        "name":"三国演义",
        "author":"罗贯中"
    },{
        "name":"红楼梦",
        "author":"曹雪芹"
    }]
    return render_template('control.html', age = age ,books = books)

#6.过滤器
@app.route('/filter')
def filter_demo():
    p3= User("过滤器","filter@qq.com")
    mytime = datetime.now()
    return render_template('filter.html',user = p3 ,mytime = mytime)

#7.自定义过滤器，过滤器命名为dformate
def datetime_formate(value,format="%Y年%m月%d日 %H:%M"):
    return value.strftime(format)
app.add_template_filter(datetime_formate,'dformate')

#8.post请求跳转页面
@app.route('/submit', methods=['POST'])
def submit():
    name = request.form['name']
    return f'你好，{name}！'

#8.模板继承
@app.route('/child1')
def child1():
    return render_template("child1.html")

#8.模板继承
@app.route('/child2')
def child2():
    return render_template("child2.html")

#9.访问静态文件
@app.route('/static')
def staticimg():
    return render_template("static.html")


if __name__ == '__main__':

    app.run(debug=True)